#ifndef __XMLCONFIG_H__
#define __XMLCONFIG_H__

#include "tinyxml.h"
#include "Manager.h"

vector<string> split(string str, string separator)  
{  
	vector<string> result;  
	int cutAt;  
	while( (cutAt = str.find_first_of(separator)) != str.npos )  
	{  
		if(cutAt > 0)  
		{  
			result.push_back(str.substr(0, cutAt));  
		}  
		str = str.substr(cutAt + 1);  
	} 

	if(str.length() > 0)  
	{  
		result.push_back(str);  
	}

	return result;  
} 

void GetAppPath(char *path)
{
	if (NULL == path)
		return;

	char path_buffer[_MAX_PATH] = {0};
	char drive[_MAX_DRIVE] = {0};
	char dir[_MAX_DIR] = {0};;
	char fname[_MAX_FNAME] = {0};;
	char ext[_MAX_EXT] = {0};;
	GetModuleFileNameA(NULL,path_buffer,_MAX_PATH);
	_splitpath(path_buffer, drive, dir, fname, ext);
	strcat(path, drive);
	strcat(path, dir);
}

bool GetConfig(vector<AppConfig> &vecApp)
{
	char szAppPath[MAX_PATH] = {0};
	GetAppPath(szAppPath);

	char szConfigPath[MAX_PATH] = {0};
	sprintf_s(szConfigPath, "%s/config.xml", szAppPath);

	TiXmlDocument doc;                                
	if (!doc.LoadFile(szConfigPath)) {  
		return false;  
	}

	vector<string> vecCurPath = split(szAppPath, "\\");

	TiXmlElement* rootElement = doc.RootElement();   
	TiXmlElement* programElement = rootElement->FirstChildElement();   
	for (; programElement != NULL; programElement = programElement->NextSiblingElement() ) 
	{  
		AppConfig appConfig;

		TiXmlAttribute* attributeOfStudent = programElement->FirstAttribute();
		for (;attributeOfStudent != NULL; attributeOfStudent = attributeOfStudent->Next() ) 
		{  
			if (strcmp(attributeOfStudent->Name(), "name") == 0)
				appConfig.strName = attributeOfStudent->Value();
			else if (strcmp(attributeOfStudent->Name(), "path") == 0)
				appConfig.strPath = attributeOfStudent->Value();
			else if (strcmp(attributeOfStudent->Name(), "params") == 0)
				appConfig.strParam = attributeOfStudent->Value();
			       
		}  

		vector<string> vecProPath = split(appConfig.strPath, "\\");

		string strAllPath;
		int nCount = 0;
		bool bFirst = true;

		for (int i = 0; i < (int)vecProPath.size(); i++)
		{
			string &str = vecProPath[i];
			
			if (str == "..")
			{
				nCount++;
			}

			if (str != ".." && str != ".")
			{
				if (bFirst)
				{
					for (int j = 0; j < (int)vecCurPath.size() - nCount; j++)
					{						
						strAllPath += vecCurPath[j];
						strAllPath += "\\";
					}

					bFirst = false;
				}				
				
				strAllPath += str;

				if (i < (int)vecProPath.size() - 1)
				{
					strAllPath += "\\";
				}				
			}
		}

		appConfig.strPath = strAllPath;

		vecApp.push_back(appConfig);
	} 

	return true;
}

#endif